package org.dairy.farms.interceptor.hibernate;

import org.dairy.farms.model.AuditInfo;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: gduggirala
 * Date: Jun 13, 2011
 * Time: 8:24:31 PM
 */
public class AuditListener {
    @PrePersist
    public void prePersist(Object obj){
        if(obj instanceof Auditable){
            AuditInfo auditInfo = ((Auditable) obj).getAuditInfo();
            if(auditInfo == null){
                auditInfo = new AuditInfo();
            }
            auditInfo.setCreatedBy(1l);
            auditInfo.setModifiedBy(1l);
            auditInfo.setDateCreated(new Date());
            auditInfo.setDateModified(new Date());
        }
    }

    @PreUpdate
    public void preUpdate(Object obj){
        if(obj instanceof Auditable){
            AuditInfo auditInfo = ((Auditable) obj).getAuditInfo();
            if(auditInfo == null){
                auditInfo = new AuditInfo();
            }
            auditInfo.setModifiedBy(1l);
            auditInfo.setDateModified(new Date());
        }
    }
}
